<template>
  <view>
    <Tabs :tabs="tabs" @tabsItemChange="handleTabsItemChange">
      <view class="iot-order_main">
        <view class="iot-order_item" v-for="(item, index) in orders" :key="item.order_id">
          <view class="iot-order_no_row">
            <view class="iot-order_no_text">订单编号</view>
            <view class="iot-order_no_value">{{ item.order_number }}</view>
          </view>

          <view class="iot-order_price_row">
            <view class="iot-order_price_text">订单价格</view>
            <view class="iot-order_price_value">￥{{ item.order_price }}</view>
          </view>

          <view class="iot-order_time_row">
            <view class="iot-order_time_text">订单日期</view>
            <view class="iot-order_time_value">{{ item.create_time_cn }}</view>
          </view>
        </view>
      </view>
    </Tabs>
  </view>
</template>

<script>
import Tabs from '../../components/Tabs/Tabs'
import { request } from '../../request/index.js'

export default {
  components: {
    Tabs
  },
  data() {
    return {
      orders: [],
      tabs: [
        {
          id: 0,
          value: '全部',
          isActive: true
        },
        {
          id: 1,
          value: '待付款',
          isActive: false
        },
        {
          id: 2,
          value: '待发货',
          isActive: false
        },
        {
          id: 3,
          value: '退款/退货',
          isActive: false
        }
      ]
    }
  },
  onShow(options) {
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.navigateTo({
        url: '/pages/auth/index'
      })
      return
    }
    let pages = getCurrentPages()
    let currentPage = pages[pages.length - 1]
    // 3 获取url上的type参数
    const { type } = currentPage.options
    this.changeTitleByIndex(type - 1)
    this.getOrders(type)
  },
  methods: {
    // 获取订单列表的方法
    async getOrders(type) {
      const res = await request({
        url: '/my/orders/all',
        data: {
          type
        }
      })
      this.orders.res.orders.map((v) => ({
        ...v,
        create_time_cn: new Date(v.create_time * 1000).toLocaleString()
      }))
    },

    // 根据标题索引来激活选中 标题数组
    changeTitleByIndex(index) {
      // 2 修改源数组
      let { tabs } = this
      tabs.forEach((v, i) =>
        i === index ? (v.isActive = true) : (v.isActive = false)
      )
      // 3 赋值到data中
      this.tabs
    },

    handleTabsItemChange(e) {
      // 1 获取被点击的标题索引
      const { index } = e.detail
      this.changeTitleByIndex(index)
      // 2 重新发送请求 type=1 index=0
      this.getOrders(index + 1)
    }
  }
}
</script>
<style>
@import './index.css';
</style>
